import React, { Component } from 'react';
import { Modal, Form, Button, Icon, Input, TimePicker, Row, Col } from 'antd';
import moment from 'moment';
import styles from './Activity.less';

const FormItem = Form.Item;
const format = 'HH:mm';

export default Form.create()(
	class extends Component {
		num = 100;
		initTimes = [];
		state = {
			actTimes: null,
		};
		componentWillReceiveProps(nextProps) {
			const { actTimes } = nextProps;
			if (actTimes && this.props.actTimes !== actTimes) {
				this.setState({
					actTimes: nextProps.actTimes,
				});
				this.initTimes = [];
			}
		}

		transformStrToArr = string => {
			const arr = string.split(',').map(item => item.split('-'));
			const values = arr.map(time => {
				return time.map(t => moment(t, format));
			});
			return values;
		};

		remove = k => {
			const { form } = this.props;
			const keys = form.getFieldValue('keys');
			if (keys.length === 1) {
				return;
			}
			const index = keys.findIndex(item => item === k);
			this.initTimes.splice(index, 1);
			form.setFieldsValue({
				keys: keys.filter(key => key !== k),
			});
		};

		add = k => {
			const {
				props: { form },
			} = this;
			this.num += 1;
			const keys = form.getFieldValue('keys');
			const index = keys.findIndex(key => key === k);
			keys.splice(index + 1, 0, this.num);
			this.initTimes.splice(index + 1, 0, undefined);
			form.setFieldsValue({
				keys,
			});
		};

		timeChange = (name, memt) => {
			const { form } = this.props;
			form.setFieldsValue({
				[name]: moment( format),
			});
		};
		// 将数据转换成二维数组的值进行返回
		getTimes = () => {
			const { form } = this.props;
			const times = form.getFieldsValue().times;
			if (Array.isArray(times)) {
				return times.filter(i => i);
			} else {
				const keys = Object.keys(times);
				return keys.map(key => times[key]);
			}
		};

		validataStartTime = (rule, value, cb) => {
			const arr = this.getTimes();
			const curIndex = arr.findIndex(item => item[0] === value);
			const times = arr.filter((item, index) => item[0] !== value && index < curIndex);
			// 选中的时间在之前已有的时间段范围内
			const interval = times.some(
				([start, end]) =>
					(start && end && value.isBetween(start, end)) ||
					(start && start.format(format) === value.format(format))
			);
			if (interval) {
				return cb('选择的时间段有冲突');
				// 其余时间段包含在已选择的时间段之内
			} else if (arr[curIndex][1]) {
				this.props.form.validateFields([`times[${curIndex}][1]`], { force: true });
				return cb();
			}
			return cb();
		};

		validataEndTime = (rule, value, cb) => {
			const arr = this.getTimes();
			const curIndex = arr.findIndex(item => item[1] === value);
			const times = arr.filter((item, index) => item[1] !== value && index < curIndex);
			// 选中的时间在之前已有的时间段范围内
			const interval = times.some(
				([start, end]) =>
					(start && end && value.isBetween(start, end)) ||
					(end && end.format(format) === value.format(format))
			);
			const condiArr = arr.find(item => item[1] === value);
			const startTime = condiArr ? condiArr[0] : null;
			if (interval) {
				return cb('选择的时间段有冲突');
			} else if (startTime) {
				if (value.isSame(startTime) || value.isBefore(startTime)) {
					return cb('结束时间不能小于开始时间');
				}
				const oth = times.some(
					([start, end]) =>
						(start && start.isBetween(startTime, value)) || (end && end.isBetween(startTime, value))
				);
				return oth ? cb('选择的时间段有冲突') : cb();
			}
			return cb();
		};

		judgeError = () => {
			const { form } = this.props;
			const timeErrors = form.getFieldsError().times;
			if (Array.isArray(timeErrors)) {
				return !!timeErrors.find(time => {
					return !!time.find(item => item);
				});
			} else {
				const keys = Object.keys(timeErrors);
				return !!keys.find(key => {
					return !!timeErrors[key].find(item => item);
				});
			}
		};

		handleSubmit = e => {
			e.preventDefault();
			this.props.form.validateFields(['times'], { firstFields: true, force: true }, (err, values) => {
				if (!err) {
					console.log('Received values of form: ', values);
					let arr;
					if (Array.isArray(values.times)) {
						arr = values.times.filter(i => i).map(value => {
							return value.map(v => v.format(format));
						});
					} else {
						arr = Object.keys(values.times).map(value => {
							return values.times[value].map(v => v.format(format));
						});
					}
					this.props.periodOk(arr);
					this.props.form.resetFields();
				}
			});
		};

		handleCancel = () => {
			this.props.periodCancel();
			this.props.form.resetFields();
		};

		render() {
			const { getFieldDecorator, getFieldValue } = this.props.form;
			const { visible } = this.props;
			const { timeChange, add, num, validataStartTime, validataEndTime } = this;
			const { actTimes } = this.state;
			const formItemLayoutWithOutLabel = {
				wrapperCol: {
					xs: { span: 20, offset: 2 },
					sm: { span: 20, offset: 2 },
				},
			};
			if (!this.initTimes.length) {
				this.initTimes = actTimes ? this.transformStrToArr(actTimes) : [];
			}
			const indexArr = this.initTimes.map((t, i) => i);
			getFieldDecorator('keys', { initialValue: actTimes ? [...indexArr] : [num] });
			const keys = getFieldValue('keys');
			const formItems = keys.map((k, index) => {
				let startMemt;
				let endMemt;
				if (this.initTimes.length && this.initTimes[index]) {
					startMemt = this.initTimes[index][0];
					endMemt = this.initTimes[index][1];
				} else if (index === 0) {
					startMemt = moment(moment().minute(0), format);
					endMemt = moment(
						moment()
							.add(1, 'hour')
							.minute(0),
						format
					);
				} else {
					startMemt = null;
					endMemt = null;
				}
				return (
					<Row type="flex" align="center" justify="center" gutter={8} key={`${k}_${index}`}>
						<Col span={8}>
							<FormItem {...formItemLayoutWithOutLabel} required={false}>
								{getFieldDecorator(`times[${k}][0]`, {
									initialValue: startMemt,
									validateFirst: true,
									rules: [
										{
											required: true,
											message: '请选择开始时间',
										},
										{
											type: 'object',
											validator: validataStartTime,
										},
									],
								})(
									<TimePicker
										format={format}
										minuteStep={1}
										onChange={memt => {
											timeChange(`times[${k}][0]`, memt);
										}}
									/>
								)}
							</FormItem>
						</Col>
						<Col span={1}>
							<span className={styles.minus}> - </span>
						</Col>
						<Col span={8}>
							<FormItem {...formItemLayoutWithOutLabel} required={false}>
								{getFieldDecorator(`times[${k}][1]`, {
									initialValue: endMemt,
									validateFirst: true,
									rules: [
										{
											required: true,
											message: '请选择结束时间',
										},
										{
											type: 'object',
											validator: validataEndTime,
										},
									],
								})(
									<TimePicker
										format={format}
										minuteStep={1}
										onChange={memt => {
											timeChange(`times[${k}][1]`, memt);
										}}
									/>
								)}
							</FormItem>
						</Col>
						<Col span={3}>
							<Icon type="plus-circle" onClick={() => add(k)} className={styles['dynamic-add-button']} />
							{keys.length > 1 && index !== 0 ? (
								<Icon
									className={styles['dynamic-delete-button']}
									type="minus-circle-o"
									disabled={keys.length === 1}
									onClick={() => this.remove(k)}
								/>
							) : null}
						</Col>
					</Row>
				);
			});
			return (
				<Modal
					visible={visible}
					title="添加编辑时间段"
					onOk={this.handleSubmit}
					onCancel={this.handleCancel}
				>
					<Form>{formItems}</Form>
				</Modal>
			);
		}
	}
);
